<template>
  <div>
    <div style="padding: 20px">
      <el-card>
        <div slot="header">
          <span style="font-size: 18px">{{ title }}</span>
        </div>
        <el-form :model="addFormdata" :rules="rules" ref="addRef">
          <el-form-item prop="subject" label-width="120px"
            ><span slot="label" style="font-size: 16px">学科：</span
            ><el-select
              placeholder="请选择"
              v-model="addFormdata.subjectID"
              style="width: 400px"
              @change="changeSubject"
              auto-complete="off"
            >
              <el-option
                v-for="item in subjects"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option> </el-select
          ></el-form-item>

          <el-form-item prop="catalog" label-width="120px"
            ><span slot="label" style="font-size: 16px">目录：</span
            ><el-select
              placeholder="请选择"
              v-model="addFormdata.catalogID"
              style="width: 400px"
            >
              <el-option
                v-for="item in directorys"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option> </el-select
          ></el-form-item>

          <el-form-item prop="enterprise" label-width="120px">
            <span slot="label" style="font-size: 16px">企业：</span
            ><el-select
              placeholder="请选择"
              v-model="addFormdata.enterpriseID"
              style="width: 400px"
            >
              <el-option
                v-for="item in companys"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option> </el-select
          ></el-form-item>

          <el-form-item prop="city" label-width="120px">
            <span slot="label" style="font-size: 16px">城市：</span>
            <el-select
              v-model="addFormdata.province"
              placeholder="请选择"
              @change="choseProvince"
              style="width: 198px; margin-right: 4px"
            >
              <el-option
                v-for="item in provinces"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="addFormdata.city"
              placeholder="请选择"
              autocomplete="on"
              @change="choseCity"
              style="width: 198px"
            >
              <el-option
                v-for="item in cities"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="direction" label-width="120px">
            <span slot="label" style="font-size: 16px">方向：</span
            ><el-select
              placeholder="请选择"
              v-model="addFormdata.direction"
              style="width: 400px"
            >
              <el-option
                v-for="item in directions"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              >
              </el-option> </el-select
          ></el-form-item>

          <el-form-item prop="questionType" label-width="120px">
            <span slot="label" style="font-size: 16px">题型：</span>
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              v-model="addFormdata.questionType"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-form-item>

          <el-form-item prop="difficulty" label-width="120px">
            <span slot="label" style="font-size: 16px">难度：</span>
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              v-model="addFormdata.difficulty"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-form-item>

          <el-form-item prop="question" label-width="120px">
            <span slot="label" style="font-size: 16px">题干：</span>
            <quillEditor
              v-model="addFormdata.question"
              :options="editorOptions"
            ></quillEditor>
          </el-form-item>

          <el-form-item
            prop="options"
            label-width="120px"
            v-if="addFormdata.questionType !== '3'"
          >
            <span slot="label" style="font-size: 16px">选项：</span>

            <el-radio-group
              v-if="addFormdata.questionType === '1'"
              v-model="isRight"
              style="display: flex; flex-direction: column"
              @change="changeRadio"
            >
              <el-radio
                style="padding: 8px 0"
                v-for="item in addFormdata.options"
                :key="item.code"
                :label="item.code"
                >{{ item.code }}： <el-input v-model="item.title"></el-input
              ></el-radio>
            </el-radio-group>

            <el-checkbox-group
              v-if="addFormdata.questionType === '2'"
              v-model="isRightGroup"
              style="display: flex; flex-direction: column"
              @change="changeCheckbox"
            >
              <el-checkbox
                style="padding: 8px 0"
                v-for="item in addFormdata.options"
                :key="item.code"
                :label="item.code"
                >{{ item.code }}： <el-input v-model="item.title"></el-input
              ></el-checkbox>
            </el-checkbox-group>

            <el-button
              type="danger"
              style="margin-top: 20px"
              :disabled="addFormdata.questionType === '1'"
              @click="addOption"
              >+增加选项和答案</el-button
            >
          </el-form-item>

          <el-form-item prop="video" label-width="120px">
            <span slot="label" style="font-size: 16px">解析视频：</span>
            <el-input
              style="width: 400px"
              v-model="addFormdata.videoURL"
            ></el-input
          ></el-form-item>

          <el-form-item prop="answer" label-width="120px">
            <span slot="label" style="font-size: 16px">答案解析：</span>
            <quillEditor
              v-model="addFormdata.answer"
              :options="editorOptions"
            ></quillEditor>
          </el-form-item>

          <el-form-item prop="remarks" label-width="120px">
            <span slot="label" style="font-size: 16px">题目备注：</span>
            <el-input
              type="textarea"
              style="width: 400px"
              v-model="addFormdata.remarks"
            ></el-input>
          </el-form-item>

          <el-form-item prop="tag" label-width="120px">
            <span slot="label" style="font-size: 16px">试题标签：</span
            ><el-select
              multiple
              allow-create
              filterable
              placeholder="请选择"
              v-model="addFormdata.tags"
              style="width: 400px"
            >
              <el-option
                v-for="item in tags"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              >
              </el-option> </el-select
          ></el-form-item>

          <el-form-item label-width="120px">
            <el-button
              type="primary"
              style="width: 110px; height: 40px"
              @click="submit"
              >确认提交</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { list } from '@/api/hmmm/companys'
import { simple } from '@/api/hmmm/subjects'
import { add, detail, update } from '@/api/hmmm/questions'
import { simple as directorysSimple } from '@/api/hmmm/directorys'
import { simple as tagsSimple } from '@/api/hmmm/tags'
import ChineseDistricts from '@/utils/area'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
  ['code-block'],
  ['image', 'link']
]
export default {
  data() {
    return {
      title: '试题录入',
      ChineseDistricts: ChineseDistricts,
      data: { subjectID: null },
      subjects: [],
      directorys: [],
      direction: direction,
      questionType: questionType,
      difficulty: difficulty,
      isRight: '',
      isRightGroup: [''],
      editorOptions: {
        theme: 'snow',
        placeholder: '',
        modules: {
          toolbar: toolbarOptions
        }
      },
      directions: [],
      tags: [],
      companys: [],
      provinces: [],
      cities: [],
      shi1: [],
      str: 'EFGHIJKLMNOPQRSTUVWXYZ',
      addFormdata: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: 1,
        difficulty: 1,
        remarks: '',
        tags: '',
        answer: '',
        question: '',
        videoURL: '',
        options: [
          { isRight: 0, code: 'A', title: '', img: '' },
          { isRight: 0, code: 'B', title: '', img: '' },
          { isRight: 0, code: 'C', title: '', img: '' },
          { isRight: 0, code: 'D', title: '', img: '' }
        ]
      },
      rules: {
        subject: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalog: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterprise: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        city: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [{ required: true, trigger: 'blur' }],
        difficulty: [{ required: true, trigger: 'blur' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入答案', trigger: 'blur' }]
      }
    }
  },
  components: { quillEditor },
  created() {
    this.getCompanyList()
    this.getCityData()
    this.getDirections()
    this.getSubjects()
  },
  mounted() {
    this.$refs.addRef.resetFields()
    // this.addFormdata = {}
    if (this.$store.state.row.row.id) {
      console.log('执行handleEdit')
      this.handleEdit()
    }
  },
  beforeDestroy() {
    this.$refs.addRef.resetFields()
  },
  methods: {
    async getCompanyList() {
      const {
        data: { items }
      } = await list({ pagesize: 10000 })
      // console.log(items)
      items.forEach(item => {
        this.companys.push({ value: item.id, label: item.company })
      })
    },
    async getSubjects() {
      const { data } = await simple()
      this.subjects = data
    },
    async changeSubject(val) {
      // console.log(val)
      this.addFormdata.subjectID = val
      const { data } = await directorysSimple(this.data)
      this.directorys = data
      const { data: data2 } = await tagsSimple(this.data)
      this.tags = data2
    },
    // 获取全国城市
    getCityData() {
      this.ChineseDistricts.forEach(item => {
        // console.log(item)
        item.cityList?.forEach(item2 => {
          this.provinces.push({
            id: item2.code,
            label: item2.name,
            children: item2.areaList
          })
        })
      })
    },
    // 选省
    choseProvince(e) {
      this.cities = []
      this.provinces.forEach(item => {
        if (item.id === e) {
          // console.log(item)
          this.addFormdata.province = item.label
          this.shi1 = item.children
          this.addFormdata.city = item.children[0].name
          this.shi1.forEach(citem => {
            this.cities.push({
              id: citem.code,
              label: citem.name
            })
          })
        }
      })
    },
    // 选市
    choseCity(e) {
      this.cities.forEach(item => {
        // console.log(item)
        if (item.id === e) {
          this.addFormdata.city = item.label
        }
      })
    },
    getDirections() {
      direction.forEach((item, index) => {
        this.directions.push({ value: index, label: item })
      })
    },
    changeRadio() {
      this.addFormdata.options.forEach(item => {
        item.code === this.isRight ? (item.isRight = 1) : ''
      })
    },
    changeCheckbox() {
      this.addFormdata.options.forEach(item => {
        this.isRightGroup.forEach(item2 => {
          item.code === item2 ? (item.isRight = 1) : ''
        })
      })
    },
    async submit() {
      try {
        this.$refs.addRef.validate()
        if (this.addFormdata.tags !== '')
          this.addFormdata.tags = this.addFormdata.tags.join(',')
        this.addFormdata.questionType += ''
        this.addFormdata.difficulty += ''
        console.log(this.addFormdata)
        if (this.title === '试题录入') {
          await add(this.addFormdata)
          this.$message.success('添加成功')
        } else {
          const { data } = await update(this.addFormdata)
          data.success ? this.$message.success('修改成功') : ''
        }
        this.$refs.addRef.resetFields()
        this.$router.push('/questions/list')
      } catch (error) {
        console.dir(error)
      }
    },
    addOption() {
      this.addFormdata.options.push({
        isRight: false,
        code: this.arr[0],
        title: '',
        img: ''
      })
      this.arr.shift()
    },
    async handleEdit() {
      this.title = '试题修改'
      const row = this.$store.state.row.row
      console.log(row)
      const { data } = await detail({ id: row.id })
      console.log(data)

      if (data.questionType === '1') {
        data.options.forEach(item => {
          item.isRight === 1 ? (this.isRight = item.code) : ''
          // item.code === this.isRight ? (item.isRight = 1) : ''
        })
      } else if (data.questionType === '2') {
        data.options.forEach(item => {
          item.isRight === 1 ? this.isRightGroup.push(item.code) : ''
          // this.isRightGroup.forEach(item2 => {
          //   item.code === item2 ? (item.isRight = 1) : ''
          // })
        })
      }

      data.questionType = +data.questionType
      data.difficulty = +data.difficulty

      const res = await directorysSimple({ id: row.id })
      this.directorys = res.data

      // tags下拉框数据
      const res1 = await tagsSimple({ id: row.id })
      this.tags = res1.data

      this.addFormdata.options = { ...data.options }
      this.addFormdata = { ...data }
      if (data.tags !== '') this.addFormdata.tags = data.tags.split(',')

      console.log(this.addFormdata)
    }
  },
  computed: {
    arr() {
      return this.str.split('')
    }
  }
}
</script>

<style scoped lang="scss">
.el-card {
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border: 1px solid #ebeef5;
  background-color: #fff;
  color: #303133;
  transition: 0.3s;
  border-radius: 4px;
  overflow: hidden;
  .el-form {
    .el-form-item {
      margin-bottom: 22px;
      .el-select {
        width: 400px;
      }
      quillEditor {
        width: 800px;
      }
      ::v-deep .ql-editor {
        min-height: 200px;
      }
      .el-radio-group,
      .el-checkbox-group {
        .el-input {
          width: 240px;
        }
      }
    }
  }
}
</style>
